package com.baking.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baking.dao.MenuMapper;
import com.baking.model.Menu;
import com.baking.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

@Service
public class MenuServiceImpl implements IMenuService {

    @Autowired
    MenuMapper menuMapper;

    @Override
    public String getMenuList(Integer roleId) {
        String createMenu  = null;
        try {
            List<Menu> menuList = menuMapper.getMenuList(roleId);
            createMenu = createMenu(menuList);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return createMenu;
    }

    @Override
    public List<Menu> getMenuPanel() {
        List<Menu> menuList  = null;
        try {
             menuList = menuMapper.getMenuList(null);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return menuList;
    }

    public String createMenu(List<Menu> menuList){
        JSONArray jsonArray = new JSONArray();
        //先获取父类，再获取子类，一次类推
        for (int i=0;i<menuList.size();i++){
            Menu tmp1 = menuList.get(i);
            Integer id = tmp1.getParentId();
            if(tmp1.getParentId()==null || 0==tmp1.getParentId()){
                JSONObject jsonObject = createBrachMenu(tmp1,menuList);
                jsonArray.add(jsonObject);
            }
        }
        return jsonArray.toString();
    }

    public JSONObject createBrachMenu(Menu menu,List<Menu> menuList){
        String fatherMenu = JSON.toJSONString(menu);
        JSONObject jsonObject = JSON.parseObject(fatherMenu);
        JSONArray jsonArray = new JSONArray();
        for (Menu menu1:menuList){
            if (menu.getParentId()!=null &&menu.getId().equals(menu1.getParentId())){
                jsonArray.add(menu1);
            }
        }
        jsonObject.put("children",jsonArray);
        return jsonObject;
    }
}
